//
//  Data+Extension.swift
//  SwiftExercise
//
//  Created by 罗宗庆 on 2021/6/23.
//

import UIKit

//仿微信时间
extension Date{
    
    
    //Date.createTime(createAt:你的时间串).usresDateString
    
    static func createTime(createAt:String)->Date{
        let dateFormate = DateFormatter()
        dateFormate.dateFormat = "yyyy-mm-dd HH:mm:ss"
        dateFormate.locale = Locale(identifier: "en_US")
        let createAtDate = dateFormate.date(from: createAt)!
        return createAtDate
    }
    
    var userDateString:String{
        let dateFormate = DateFormatter()
        dateFormate.locale = Locale(identifier: "en_US")
        
        if isThisYear(createAtDate: self) {
            let currentCalendar = Calendar.current
            if currentCalendar.isDateInToday(self) {
                let timeInterval:TimeInterval = abs(self.timeIntervalSinceNow)
                if timeInterval < 60 {
                    return "刚刚"
                }else if timeInterval < 3600{
                    let result = timeInterval / 60
                    return "\(Int(result))分钟前"
                }else{
                    let result = timeInterval / 3600
                    return "\(Int(result))小时前"
                }
            }else if currentCalendar.isDateInYesterday(self){
                dateFormate.dateFormat = "昨天 HH:mm"
            }else{
                dateFormate.dateFormat = "mm-dd"
            }
        }else{
            dateFormate.dateFormat = "yyyy-MM-dd"
        }
        return dateFormate.string(from: self)
    }
    
    private func isThisYear(createAtDate:Date)->Bool{
        let dateFormter = DateFormatter()
        dateFormter.dateFormat = "yyyy"
        dateFormter.locale = Locale(identifier: "en_US")
        let createAtYear = dateFormter.string(from: createAtDate)
        let currentDateYear = dateFormter.string(from: Date())
        return currentDateYear == createAtYear
    }
}
